package com.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.common.mybatis.Page;
import com.common.utils.base.UuidUtil;
import com.entity.FileRel;
import com.entity.TradeRel;
import com.entity.User;
import com.repository.UserDao;
import com.service.base.BaseServiceImp;

@Service("UserService")
public class UserServiceImpl extends BaseServiceImp<User> implements UserService{
	@Autowired
	private TradeRelService tradeRelService;
	@Autowired
	private FileRelService fileRelService;
	@Autowired
	private UserDao userDao;

	@Override
	@Transactional
	public String register(User u) {
		u.setId(UuidUtil.get32UUID());
		u.setCredit(100);
		baseDao.insert(u);
		// 添加默认头像
		FileRel rel = new FileRel();
		rel.setRelevanceId(u.getId());
		rel.setRelevanceTable("user");
		rel.setRemark("portrait");
		rel.setFileId("03");
		rel.setFileType("image");
		rel.setUrlInfor("upload/file/empty-img.png");
		fileRelService.insert(rel);
		return u.getId();
	}
	
	@Override
	@Transactional
	public String insert(User o, List<FileRel> rels) {
		o.setId(UuidUtil.get32UUID());
		if(o.getCredit() == null) o.setCredit(100);
		o.setLoginId(UuidUtil.get32UUID());
		//添加用户行业关系表
		TradeRel rel = new TradeRel();
		rel.setUserId(o.getId());
		rel.setTradeId(o.getUserTradeId());
		rel.setUserTypeId(o.getUserTypeId());
		tradeRelService.insert(rel);
		//批量添加附件关系
		for (FileRel fr : rels) {
			fr.setRelevanceId(o.getId());
			fr.setRelevanceTable("user");
			fr.setUploader("Admin");
			fileRelService.insert(fr);
		}
		baseDao.insert(o);
		return o.getId();
	}

	@Transactional
	public void delete(User o) {
		//删除用户行业关系表
		TradeRel rel = new TradeRel();
		rel.setUserId(o.getId());
		List<TradeRel> rels = tradeRelService.find(rel);
		tradeRelService.deleteBatch(rels);;
		//TODO 删除附件关系表
		super.delete(o);
	}
	
	@Override
	@Transactional
	public void update(User o, List<FileRel> rels) {
		//更新用户行业关系表
		TradeRel rel = new TradeRel();
		rel.setUserId(o.getId());
		rel = tradeRelService.find(rel).get(0);
		rel.setTradeId(o.getUserTradeId());
		rel.setUserTypeId(o.getUserTypeId());
		tradeRelService.update(rel);
		//更新附件关系表
		if(rels != null && rels.size() > 0 ){
			for (FileRel fr : rels) {
				fr.setRelevanceId(o.getId());
				fr.setRelevanceTable("user");
				fr.setUploader("Admin");
				fileRelService.insert(fr);
			}
		}
		baseDao.update(o);
	}

	@Override
	public List<User> findUser(User user) {
		return userDao.findUser(user);
	}

	@Override
	public Page<User> findDetailByPage(User o, Page<User> page) {
		page.setResults(userDao.findDetailByPage(o, page));
		return page;
	}

	@Override
	public List<String> findCompany(User user) {
		return userDao.findCompany(user);
	}
	
}
